<template>
    <div class="assignment-header">
        <el-button @click="$router.go(-1)" link class="back-button">
            <img src="@/assets/svgs/left.svg" alt="Back" class="back-icon" />
        </el-button>
        <div class="information">聊天室</div>
        <div class="user-info" @click="toggleDropdown">
            <img class="avatar" :src="userInfo?.avatarUrl" alt="User Avatar">
            <span class="username22">{{ userInfo?.nick_name }}</span>
            <img class="dropdown-arrow" src="@/assets/svgs/downnarrow.svg" alt="Dropdown Arrow">
            <div v-if="dropdownVisible" class="dropdown-menu">
                <p @click="$router.push('/teacher/information')">个人信息</p>
                <p @click="$router.push('/login')">退出登录</p>
            </div>
        </div>
    </div>
    <div class="chat_room">
        <div class="chat_left">
            <div class="chat_left1">
                <img src="@/assets/images/usagi1.jpg" alt="avatar" class="usertouxiang">
                <div class="user_name">{{ user.userName }}</div>
            </div>
            <div class="chat_left2">
                <!-- 群聊选项 -->
                <div class="chat_left21">
                    <img src="@/assets/images/yonghutouxiang.png" alt="avatar" class="avatar-icon1">
                    <div class="username" @click="changeChatUser('group'), chatUser = 'group'" style="cursor: pointer;">
                        群聊</div>
                    <span style="font-size: 12px;color: limegreen; margin-left: 5px"
                        v-if="chatUser === 'group'">chatting...</span>
                </div>
                <div class="chat_left21">
                    <div class="username">在线用户</div>
                </div>
                <!-- 动态获取在线用户，请用两个浏览器登录不同用户进入聊天室页面 -->
                <div v-for="user in users" :key="user.username" class="chat_left21" :id="user.id">
                    <img src="@/assets/images/yonghutouxiang2.png" alt="avatar" class="avatar-icon1">
                    <div class="username" @click="changeChatUser(user.username), chatUser = user.username"
                        style="cursor: pointer;">
                        {{ user.username }}
                    </div>
                    <span style="font-size: 12px;color: limegreen; margin-left: 5px"
                        v-if="user.username === chatUser">chatting...</span>
                </div>
            </div>
        </div>
        <div class="chat_right">
            <div class="chat_right1">
                <div class="username1">聊天室({{ chatUser }})</div>
            </div>
            <div class="chat_right2">
                <div class="messages" v-html="content"></div>
                <div class="input-area">
                    <el-input v-model="text" placeholder="请输入内容"
                        @keyup.enter="chatUser === 'group' ? groupsend() : send()" />
                </div>
                <el-button type="primary" @click="chatUser === 'group' ? groupsend() : send()"
                    class="input-button1">发送</el-button>
            </div>
        </div>
    </div>
    <div class="chat_function">
        <span class="splan">教学计划表</span><br><br><br>
        <div class="timeline-container">
            <div class="timeline-step" v-for="(item, index) in backendData" :key="index">
                <div :class="['timeline-dot', {
                    'clicked-dot':
                        clickedIndexes.includes(index)
                }]"></div>
                <button class="timeline-button" @click="handleClick(index, item.route)">
                    {{ item.event }}
                </button>
                <div class="timeline-line" v-if="index < backendData.length - 1"></div>
            </div>
        </div>
    </div>
    <div class="record">
        <span class="splan2">教学录音</span>
        <span :class="{ 'recording-state': recordstate === '正在录音', 'not-recording-state': recordstate === '现在没有录音' }">{{
            recordstate }}</span>
        <div class="recording1">
            <audio ref="player" controls class="audio-player"></audio>
            <button ref="recordBtn" class="record-btn">录音</button>
            <a ref="download" id="download" download="录音.ogg"></a>
        </div>
    </div>
    <!-- <div class="recording3">
        <img class="dashboard-icon" src="@/assets/svgs/jiugong.svg" @click="$router.push('/teacher/dashboard')"
            alt="Logo" />
    </div> -->
</template>


<script setup>
import { ref, onMounted } from 'vue';
import { useRouter } from 'vue-router';
import userAvatar from '@/assets/images/usagi2.png';
import { getUserInfo } from "@/api/login";
import { ElMessage } from 'element-plus';
import { getChatHistory } from "@/api/chatroom";
import { informationService } from '@/api/personnal-information';
import { useClassIdStore } from '@/stores/classId.js';


// 定义响应式数据
const userInfo = ref(null);

const fetchUserInfo = async () => {
    try {
        const result = await informationService();
        const userData = result.data;
        userInfo.value = {
            userId: userData.userId,
            avatarUrl: userData.avatar,
            user_name: userData.userName,
            nick_name: userData.nickName
        };
    } catch (error) {
        console.error('获取用户信息失败:', error);
    }
};
fetchUserInfo();

const router = useRouter();

const dropdownVisible = ref(false);
const toggleDropdown = () => {
    dropdownVisible.value = !dropdownVisible.value;
};

const messages1 = ref([
    { user: 'you', text: '欢迎来到聊天室', avatar: userAvatar },
]);

const isCollapse = ref(false);
const users = ref([]);
const chatUser = ref('');
const text = ref("");
const messages = ref([]);
const content = ref('');

// 定义 user 变量
const user = ref('');

// 模拟后端数据
const backendData = ref([
    { event: '上课', route: '' },
    { event: '签到', route: '/teacher/signin/teacher' },
    { event: '发布课堂反馈问卷', route: '/teacher/feedback/card' },
    { event: '布置作业', route: '/teacher/assignment/assign_homework' },
    { event: '上传课堂总结', route: '/teacher/record/card' },
    { event: '下课', route: '/teacher/dashboard' }
]);

// 存储已点击步骤的索引
const clickedIndexes = ref([]);

// 从 localStorage 中获取已点击的索引
const getClickedIndexesFromStorage = () => {
    const storedIndexes = localStorage.getItem('clickedTimelineIndexes');
    return storedIndexes ? JSON.parse(storedIndexes) : [];
};

// 将已点击的索引保存到 localStorage
const saveClickedIndexesToStorage = () => {
    localStorage.setItem('clickedTimelineIndexes', JSON.stringify(clickedIndexes.value));
};

// 处理点击事件的函数
const handleClick = (index, route) => {
    const indexInClicked = clickedIndexes.value.indexOf(index);
    if (indexInClicked > -1) {
        clickedIndexes.value.splice(indexInClicked, 1);
    } else {
        clickedIndexes.value.push(index);
    }
    saveClickedIndexesToStorage();

    if (route) {
        router.push({
            path: route,
            query: { fromChat: 'true' }
        });
    }
};

// 组件挂载时从 localStorage 中恢复已点击的索引，并确保"上课"步骤索引存在
onMounted(() => {
    const storedIndexes = getClickedIndexesFromStorage();
    if (!storedIndexes.includes(0)) {
        storedIndexes.push(0);
    }
    clickedIndexes.value = storedIndexes;
    saveClickedIndexesToStorage();
});

let socket;

// 发送消息方法
const send = () => {
    if (!chatUser.value) {
        alert("请选择聊天对象");
        return;
    }
    if (!text.value) {
        alert("请输入内容");
    } else {
        if (typeof (WebSocket) === "undefined") {
            console.log("您的浏览器不支持WebSocket");
        } else {
            const classIdStore = useClassIdStore();
            const classId = classIdStore.classId;
            console.log("您的浏览器支持WebSocket");
            let message = { from: user.value.userName, to: chatUser.value, text: text.value, classId: classId }
            socket.send(JSON.stringify(message));
            messages.value.push({ user: user.value.userName, text: text.value })
            createContent(null, user.value.userName, text.value)
            text.value = '';
        }
    }
};

const groupsend = () => {
    if (!chatUser.value || ! "group") {
        alert("请选择聊天对象");
        return;
    }
    if (!text.value) {
        alert("请输入内容");
    } else {
        if (typeof (WebSocket) === "undefined") {
            console.log("您的浏览器不支持WebSocket");
        } else {
            const classIdStore = useClassIdStore();
            const classId = classIdStore.classId;
            console.log("您的浏览器支持WebSocket");
            let message = { from: user.value.userName, to: "group", text: text.value, classId: classId }
            console.log('即将发送的消息内容:', message);
            socket.send(JSON.stringify(message));
            messages.value.push({ user: user.value.userName, text: text.value })
            createContent(null, user.value.userName, text.value)
            text.value = '';
        }
    }
};

// 构建消息内容方法
const createContent = (remoteUser, nowUser, text) => {
    let html;
    let usernameHtml = '';
    if (remoteUser) {
        usernameHtml = `<div style="font-size: 12px; color: #999; margin-bottom: 2px;">${remoteUser}</div>`;
    } else if (nowUser) {
        usernameHtml = `<div style="font-size: 12px; color: #999; margin-bottom: 2px; text-align: right;">${nowUser}</div>`;
    }
    if (nowUser) {
        html = `${usernameHtml}<div class="el-row" style="padding: 5px 0">
            <div class="el-col el-col-22" style="text-align: right; padding-right: 10px">
                <div class="tip left">${text}</div>
            </div>
            <div class="el-col el-col-2">
                <span class="el-avatar el-avatar--circle" style="height: 40px; width: 40px; line-height: 40px;">
                    <img src="https://cube.elemecdn.com/3/7c/3ea6beec64369c2642b92c6726f1epng.png" style="object-fit: cover;">
                </span>
            </div>
        </div>`;
    } else if (remoteUser) {
        html = `${usernameHtml}<div class="el-row" style="padding: 5px 0">
            <div class="el-col el-col-2" style="text-align: right">
                <span class="el-avatar el-avatar--circle" style="height: 40px; width: 40px; line-height: 40px;">
                    <img src="https://cube.elemecdn.com/3/7c/3ea6beec64369c2642b92c6726f1epng.png" style="object-fit: cover;">
                </span>
            </div>
            <div class="el-col el-col-22" style="text-align: left; padding-left: 10px">
                <div class="tip right">${text}</div>
            </div>
        </div>`;
    }
    console.log(html);
    content.value += html;
};

const changeChatUser = async (newChatUser) => {

    const classIdStore = useClassIdStore();
    const classId = classIdStore.classId;
    console.log('课节id', classId);

    chatUser.value = newChatUser;
    content.value = '';
    messages.value = [];

    try {
        const sender = user.value.userName;
        console.log('请求聊天历史记录的参数：', { sender, receiver: newChatUser, classId });
        const response = await getChatHistory(sender, newChatUser, classId);
        console.log('响应对象:', response);
        console.log('响应数据类型:', typeof response);
        const history = response;
        console.log('获取到的聊天历史记录:', history);

        if (Array.isArray(history)) {
            history.forEach(msg => {
                messages.value.push({
                    from: msg.sender,
                    text: msg.message,
                    id: msg.chatMessageId
                });

                console.log('聊天记录:', msg);

                if (newChatUser === 'group') {
                    if (msg.sender === user.value.userName) {
                        createContent(null, msg.sender, msg.message);
                    } else {
                        createContent(msg.sender, null, msg.message);
                    }
                } else {
                    if (msg.sender === user.value.userName) {
                        createContent(null, msg.sender, msg.message);
                    } else {
                        createContent(msg.sender, null, msg.message);
                    }
                }
            });
        } else {
            console.error('获取的聊天历史记录不是数组:', history);
            ElMessage.error('获取历史聊天记录失败，数据格式不正确');
        }
    } catch (error) {
        console.error('获取历史聊天记录失败:', error);
        ElMessage.error('获取历史聊天记录失败，请稍后重试');
    }
};

// 初始化
const init = async () => {
    try {


        const response = await getUserInfo();
        user.value = response.data;
        const username = user.value.userName;
        if (typeof (WebSocket) === "undefined") {
            console.log("您的浏览器不支持WebSocket");
        } else {
            console.log("您的浏览器支持WebSocket");
            const socketUrl = `ws://localhost:8081/chatroom/${username}`;
            if (socket != null) {
                socket.close();
                socket = null;
            }
            socket = new WebSocket(socketUrl);
            socket.onopen = function () {
                console.log("websocket已打开");
            };
            socket.onmessage = function (msg) {
                const data = JSON.parse(msg.data);
                if (data.users) {
                    users.value = data.users.filter(u => u.username !== username);
                } else {
                    if (chatUser.value === 'group' && data.to === 'group') {
                        messages.value.push(data);
                        createContent(data.from, null, data.text);
                    } else if (chatUser.value !== 'group' && (data.from === chatUser.value || data.to === chatUser.value)) {
                        messages.value.push(data);
                        createContent(data.from, null, data.text);
                    }
                }
            };
            socket.onclose = function () {
                console.log("websocket已关闭");
            };
            socket.onerror = function () {
                console.log("websocket发生了错误");
            };
        }
    } catch (error) {
        console.error('获取用户信息失败:', error);
    }
};

onMounted(() => {
    init();
});

// 录音相关代码
const recordstate = ref('现在没有录音');
const recordBtn = ref(null);
const player = ref(null);
const download = ref(null);
let chunks = [];

const initRecording = async () => {
    if (!navigator.mediaDevices.getUserMedia) {
        console.error("浏览器不支持 getUserMedia");
        return;
    }

    try {
        const constraints = { audio: true };
        const stream = await navigator.mediaDevices.getUserMedia(constraints);
        const mediaRecorder = new MediaRecorder(stream);

        recordBtn.value.onclick = () => {
            if (mediaRecorder.state === "recording") {
                mediaRecorder.stop();
                recordBtn.value.textContent = "录音结束";
                recordstate.value = '现在没有录音';
            } else {
                mediaRecorder.start();
                recordBtn.value.textContent = "录音中...";
                recordstate.value = '正在录音';
            }
        };

        mediaRecorder.ondataavailable = (e) => {
            chunks.push(e.data);
        };

        mediaRecorder.onstop = () => {
            const blob = new Blob(chunks, { type: "audio/ogg; codecs=opus" });
            chunks = [];
            const audioURL = window.URL.createObjectURL(blob);
            player.value.src = audioURL;
            download.value.innerHTML = '下载';
            download.value.href = audioURL;
        };
    } catch (error) {
        console.error("授权失败！错误信息：", error);
    }
};

onMounted(() => {
    initRecording();
});

</script>


<style scoped>
.assignment-header {
    display: flex;
    height: 7lvh;
    width: 99lvw;
    background-color: #13227A;
    color: white;
    align-items: center;
}

.back-button {
    background-color: transparent;
    width: 25px;
    height: 25px;
    color: white;
    cursor: pointer;
}

.back-icon {
    width: 25px;
    height: 25px;
}

.information {
    font-size: 28px;
    line-height: 7lvh;
    font-family: kaiti;
    margin-left: 42%;
    color: rgb(243, 245, 254);
}

.user-info {
    position: relative;
    align-items: center;
    cursor: pointer;
    display: flex;
    margin-left: 41%;
    z-index: 999;
}

.avatar {
    width: 30px;
    height: 30px;
    border-radius: 50%;
    margin-right: 10px;
}

.dropdown-arrow {
    width: 16px;
    height: 16px;
    margin-left: 5px;
}

.username22 {
    font-size: 16px;
}

.dropdown-menu {
    position: absolute;
    top: 100%;
    right: 0;
    background-color: white;
    color: black;
    border: 1px solid #ccc;
    border-radius: 4px;
    box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
    padding: 10px;
    z-index: 1000;
}

.dropdown-menu :hover {
    background-color: #f0f0f0;
    color: brown;
}

.chat_room {
    float: left;
    display: flex;
    height: 89lvh;
    width: 66lvw;
    border: 1px solid #eee;
    border-radius: 4px;
    margin-top: 1lvh;
    margin-left: 0.2lvw;
    background-color: #b9b9b9;
}

.chat_left {
    float: left;
    width: 15.6lvw;
    background-color: #b9b9b9;
}

.chat_left1 {
    float: left;
    display: flex;
    flex-direction: row;
    height: 9lvh;
    width: 15.6lvw;
    background-color: #f8f8f8;
}

.usertouxiang {
    float: left;
    width: 8lvh;
    height: 8lvh;
    margin-top: 0.35lvh;
    margin-left: 0.5lvh;
    border-radius: 50%;
}

.user_name {
    margin-left: 15px;
    margin-top: 33px;
    font-size: 20px;
    color: #7c7c7c;
    font-family: kaiti;
    font-weight: 600;
}

.chat_left2 {
    float: left;
    flex-direction: column;
    height: 79.9lvh;
    width: 15.6lvw;
    margin-top: 0.1lvh;
    max-height: 89lvh;
    overflow-y: auto;
    background-color: #f8f8f8;
}

.chat_left21 {
    display: flex;
    align-items: center;
    height: 7lvh;
    width: 15.6lvw;
    background-color: #ffffff;
    border: 0px solid #2084ff;
    border-bottom: 1px solid #b9b9b9;
    white-space: nowrap;
    overflow: hidden;
}

.chat_left21:hover {
    background-color: #2084ff;
}

.avatar-icon1 {
    width: 5.5lvh;
    height: 5.5lvh;
    margin-top: 0.5lvh;
    margin-left: 0.5lvh;
    border-radius: 50%;
}

.username {
    margin-left: 10px;
    margin-top: 15px;
    font-size: 22px;
    color: #585454;
    font-family: fangsong;
    font-weight: 700;
}

.username1 {
    margin-left: 15px;
    margin-top: 20px;
    font-size: 28px;
    color: #565656;
    font-family: kaiti;
    font-weight: 600;
}

.chat_message {
    margin-bottom: 10px;
    padding: 10px;
    background-color: #f8f8f8;
    border-radius: 5px;
}

.chat_message span {
    color: #333;
}

.chat_right {
    float: left;
    height: 89lvh;
    width: 50.26lvw;
    margin-left: 0.04lvw;
}

.chat_right1 {
    float: left;
    height: 9lvh;
    width: 50.26lvw;
    background-color: #f8f8f8;
}

.chat_right2 {
    float: left;
    height: 79.8lvh;
    width: 50.26lvw;
    margin-top: 0.1lvh;
    background-color: #f8f8f8;
}

.messages {
    flex: 1;
    max-height: 70.6lvh;
    overflow-y: auto;
    padding: 10px;
}

.message1 {
    margin-bottom: 10px;
}

.message21 {
    margin-bottom: 10px;
    overflow: hidden;
}

.message-content {
    display: flex;
    float: left;
    max-width: 60%;
    margin-left: 1px;
}

.message-content2 {
    float: right;
    max-width: 60%;
    border-radius: 50%;
}

.user {
    background-color: #ffffff;
    color: rgb(47, 45, 45);
    padding: 5px 10px;
    border-radius: 5px;
    margin-right: 5px;
    box-shadow: 0 2px 4px rgba(0, 0, 0, 0.2);
}

.other {
    background-color: #f9f9f9;
    color: #333;
    padding: 5px 10px;
    border-radius: 5px;
    margin-left: 5px;
}

.input-area {
    display: flex;
    align-items: center;
    margin-top: 90lvh;
    margin-left: 14.8lvw;
    position: fixed;
    top: 20px;
    left: 30px;
    width: 45.3lvw;
    height: 5lvh;
}

.input-button1 {
    display: flex;
    align-items: center;
    margin-top: 90.2lvh;
    margin-left: 60.5lvw;
    width: 3.85lvw;
    height: 4.4lvh;
    position: fixed;
    top: 20px;
    left: 30px;
}

.el-button {
    padding: 5px 10px;
}

.avatar-icon {
    width: 30px;
    float: left;
    height: 30px;
    border-radius: 50%;
    margin-right: 10px;
}

.avatar-icon2 {
    width: 30px;
    float: right;
    height: 30px;
    border-radius: 50%;
    margin-right: 1px;
    margin-left: 6px;
}

.message-content {
    display: flex;
    align-items: flex-start;
}

.chat_function {
    float: left;
    margin-left: 1.5lvw;
    width: 30lvw;
    height: 67lvh;
    margin-top: 2lvh;
    box-shadow: 2px 2px 4px rgba(82, 82, 82, 0.8);
}

:deep(.tip) {
    display: inline-block;
    padding: 5px 10px;
    border-radius: 5px;
    max-width: 80%;
}

:deep(.tip.left) {
    background-color: #00BFFF;
    color: white;
}

:deep(.tip.right) {
    background-color: #90EE90;
    color: white;
}

.splan {
    float: left;
    width: 23lvw;
    margin-left: 2lvw;
    margin-top: 2lvh;
    margin-bottom: 3lvh;
    font-size: 30px;
    color: #222121;
    font-family: kaiti;
    font-weight: 600;
    text-align: center;
}

.timeline-container {
    position: relative;
    padding: 5px 20px;
    width: 70%;
    margin-left: 5lvw;
    margin: 0 auto;
}

.timeline-step {
    position: relative;
    padding-left: 5lvw;
    margin-left: 2.5lvw;
    margin-bottom: 30px;
}

.timeline-dot {
    position: absolute;
    left: 0;
    top: 0;
    width: 20px;
    height: 20px;
    border-radius: 50%;
    background-color: #007BFF;
    z-index: 2;
}

.clicked-dot {
    background-color: #FF5733;
}

.timeline-button {
    display: inline-block;
    text-align: center;
    font-family: kaiti;
    font-size: 20px;
    font-weight: 550;
    white-space: nowrap;
    padding: 5px 15px;
    border: 1px solid #ccc;
    border-radius: 5px;
    background-color: #f0f0f0;
    cursor: pointer;
    transition: background-color 0.3s ease;
    margin-left: 1lvw;
}

.timeline-button:hover {
    background-color: #e0e0e0;
}

.timeline-line {
    position: absolute;
    left: 9px;
    top: 20px;
    width: 2px;
    height: calc(100% + 30px);
    background-color: #007BFF;
    z-index: 1;
}

.record {
    position: absolute;
    top: 80lvh;
    left: 68lvw;
    width: 30lvw;
    height: 17lvh;
    box-shadow: 2px 2px 4px rgba(82, 82, 82, 0.8);
}

.splan2 {
    float: left;
    width: 14lvw;
    margin-top: 2lvh;
    margin-left: 8lvw;
    margin-bottom: 2lvh;
    font-size: 28px;
    color: #222121;
    font-family: kaiti;
    font-weight: 600;
    text-align: center;
}

.recording-state {
    text-align: center;
    font-size: 18px;
    line-height: 10lvh;
    width: 8lvw;
    color: rgb(0, 98, 255);
}

.not-recording-state {
    text-align: center;
    font-size: 18px;
    line-height: 10lvh;
    width: 8lvw;
    color: rgb(255, 0, 0);
}

.recording1 {
    display: flex;
    align-items: center;
    justify-content: space-around;
    height: 5lvh;
    margin-left: 2lvw;
    width: 26lvw;
    text-align: center;
}

.audio-player {
    width: 18lvw;
}

.record-btn {
    padding: 5px 10px;
    cursor: pointer;
}

.recording3 {
    position: fixed;
    top: 90lvh;
    left: 93lvw;
    height: 5lvh;
    width: 5lvw;
}

.dashboard-icon {
    width: 3.5lvh;
    height: 3.5lvh;
    margin-left: 2.5lvw;
    margin-top: 0.7lvh;
}

.dashboard-icon:hover {
    border: 1px solid #208bfe;
}
</style>